<template>
  <div>
    <!-- Breadcrumb 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索 -->
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @closed="resetAddForm"
    >
      <!-- 添加用户主体内容 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 修改用户表单 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 用户列表区域 -->
    <el-table :data="userList" style="width: 100%" stripe border>
      <el-table-column label="#" type="index"> </el-table-column>
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="userStateChange(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <!-- 编辑按钮 -->
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row.id)"
          >
          </el-button>
          <!-- 删除按钮 -->
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="deleteUserById(scope.row.id)"
          ></el-button>
          <!-- 分配角色按钮 -->
          <el-tooltip
            :enterable="false"
            effect="dark"
            content="分配角色"
            placement="top"
          >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRoledialog(scope.row)"
            ></el-button>
          </el-tooltip>
          <!-- 分配角色对话框 -->
          <el-dialog
            title="分配角色"
            :visible.sync="setRoledialogVisible"
            width="50%"
            @close="setRoledialogClose"
          >
            <p>当前用户：{{ userInfo.username }}</p>
            <p>当前角色：{{ userInfo.role_name }}</p>
            <!-- Select 下拉菜单 为用户分配角色 -->
            <p>
              <el-select v-model="selectedRoleId" placeholder="请选择">
                <el-option
                  v-for="item in rolesList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </p>
            <span slot="footer" class="dialog-footer">
              <el-button @click="setRoledialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="saveRoleInfo"
                >确 定</el-button
              >
            </span>
          </el-dialog>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <!-- size-change pageSize 改变时会触发 每页条数
     current-change currentPage 改变时会触发 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const emailReg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/

      //   const emailReg = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/
      if (emailReg.test(value)) {
        return cb()
      } // 合法的邮箱
      return cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机的规则
    var checkMobile = (rule, value, cb) => {
      const mobileReg = /^1[0-9]{10}$/
      if (mobileReg.test(value)) {
        return cb()
      } // 合法的手机号
      return cb(new Error('请输入合法的手机号码'))
    }

    return {
      queryInfo: {
        //   搜索关键字
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 2
      },
      total: 0,
      userList: [],
      dialogVisible: false,
      //   添加用户表单
      addForm: {
        // username: 'myruby',
        // password: '123456',
        // email: '123456@qq.com',
        // mobile: '18813293912'
        username: '',
        password: '',
        email: ''
      },
      //   添加用户表单验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户
      editDialogVisible: false,
      // 根据id查询到的用户对象
      editForm: {},
      // 修改用户的验证对象
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      setRoledialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色数据列表
      rolesList: [],
      // 下拉菜单中被选中的角色id
      selectedRoleId: ''
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    //   获取用户列表
    async getUsersList () {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
      //   console.log(this.queryInfo)
      //   console.log(this.total)
    },
    // 分页器
    // 每页条数改变时会触发
    handleSizeChange (res) {
      this.queryInfo.pagesize = res
      this.getUsersList()
    },
    // 当前页码改变时触发 -->
    handleCurrentChange (res) {
      this.queryInfo.pagenum = res
      this.getUsersList()
    },
    // 用户状态改变时
    async userStateChange (res) {
      const { data } = await this.$http.put(
        `users/${res.id}/state/${res.mg_state}`
      )
      if (data.meta.status !== 200) {
        res.mg_state = !res.mg_state
        return this.$message.error(data.meta.msg)
      }

      this.$message.success('更新用户状态成功')
    },
    // 重置添加用户表单
    resetAddForm () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('/users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功！')
        // 重新获取用户数据列表
        this.getUsersList()
        // 隐藏添加用户对话框
        this.dialogVisible = false
      })
    },

    // 显示修改用户对话框
    async showEditDialog (id) {
      // 根据id请求获取用户信息
      const { data: res } = await this.$http.get('/users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭操作
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改用户表单
    editUserInfo () {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 提交成功后发起网络请求
        // console.log(this.editForm)
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            id: this.editForm.id,
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$http.error('修改用户信息失败')
        }
        //  隐藏修改用户对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getUsersList()
        // 提示用户修改成功
        this.$message.success('修改成功')
      })
    },
    // 根据id删除用户
    async deleteUserById (id) {
      const res = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '删除用户',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 如果用户确认删除 返回字符串confirm
      // 如果取消删除 返回字符串 cancle
      // console.log(res)
      if (res !== 'confirm') return this.$message.info('取消删除')
      // 发起删除用户请求
      const { data: delRes } = await this.$http.delete('users/' + id)
      if (delRes.meta.status !== 200) {
        return this.$message.error(delRes.meta.msg)
      }
      // 更新数据列表
      this.getUsersList()
      // 提示用户删除成功
      this.$message.success('删除成功')
    },
    // 显示分配角色对话框
    async showSetRoledialog (userInfo) {
      this.userInfo = userInfo
      console.log(this.userInfo)
      // 获取所有角色数据列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色数据列表失败')
      }
      // 更新数据列表
      this.rolesList = res.data
      console.log(res.data)
      this.setRoledialogVisible = true
    },
    // 为用户分配角色
    async saveRoleInfo () {
      if (!this.selectedRoleId) return this.$message.error('你没有为用户分配角色')
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.getUsersList()
      this.$message.success('分配角色成功')
      this.setRoledialogVisible = false
    },
    // 监听分配角色对话框关闭事件
    setRoledialogClose () {
      this.userInfo = {}
      this.selectedRoleId = ''
    }
  }
}
</script>

<style lang="less">
.el-breadcrumb {
  margin-bottom: 15px;
}

.el-card.is-always-shadow,
.el-card.is-hover-shadow:focus,
.el-card.is-hover-shadow:hover {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1) !important;
}
</style>
